package com.hs.srm.admin.modules.orders.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.orders.entity.*;
import com.hs.srm.admin.modules.orders.service.*;
import com.hs.srm.admin.modules.orders.vo.ScmPoItemVo;
import com.hs.srm.admin.modules.pricemanagement.entity.EssentialInformationEntity;
import com.hs.srm.admin.modules.pricemanagement.service.EssentialInformationService;
import com.hs.srm.admin.modules.requisition.controller.ProPurchRequetSapTask;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.sys.controller.SysRoleController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import com.mchange.lang.IntegerUtils;
import com.sap.conn.jco.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.Sunnykid;
import sunnykid.text.SunnykidText;
import sunnykid.web.transfer.FileTransfer;
import sunnykid.web.transfer.TransferException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购订单行项目控制层
 *
 * @author Sunnykid
 * @date 2019年3月17日
 */
@Controller
@RequestMapping("/orderItem")
public class ScmPoItemController extends AbstractController {
    Logger logger = LoggerFactory.getLogger(ProPurchRequetSapTask.class);

    private static final long serialVersionUID = 5861515635235276502L;

    @Autowired
    private ScmPoItemService scmPoItemService;

    @Autowired
    private ScmPoHeaderService scPoHeaderService;

    @Autowired
    private DeliverService deliverService;

    @Autowired
    private EssentialInformationService essentialInformation;

    @Autowired
    private DeliverRecordService deliverRecordService;

    @Autowired
    private OrderFileService orderFileService;
    @Autowired
    private VendorService vendorService;


    /**
     * 查询订单列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        ScmPoItemEntity scmPoItemEntity = new ScmPoItemEntity();
        //insertTotalPrice(scmPoItemEntity);
        PageUtils pu = this.scmPoItemService.selectDetailPage(params);
        //非生产性订单不用valToTxt
        String poFlag = null;
        if (StringUtils.isNotBlank((CharSequence) params.get("poFlag"))) {
            poFlag = params.get("poFlag").toString();
        }

        List<ScmPoItemVo> voList = (List<ScmPoItemVo>) pu.getList();
        voList = EntityUtils.valToTxt(voList);
        pu.setList(voList);

        return R.ok(pu);
    }

    @SysLog("分批发货")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public R save(@RequestBody JSONObject obj) throws Exception_Exception {
        int edition = 0;
        Map<String, String> map = null;
        if (!obj.isEmpty()) {
            map = (Map<String, String>) obj.get("ids");
        }
        if (map == null || map.size() <= 0) {
            return R.error();
        }
        // 分批发货的时间
        Date date = DateUtils.stringToDate(DateUtils.format(DateUtils.currentDateTime()), DateUtils.DATE_PATTERN);
        //获取订单item entity，获取物料描述 通知下单人
        List<ScmPoItemEntity> itemEntityList = new ArrayList<>();
        for (String key : map.keySet()) {
            // 发货的数据
            DeliverEntity deliverEntity = new DeliverEntity();
            ScmPoItemVo scmPoItemVo = this.scmPoItemService.selectByIdVo(key);
            ScmPoItemEntity scmPoItemEntity = this.scmPoItemService.selectById(key);
            itemEntityList.add(scmPoItemEntity);
            //4：同步SAP，2：分批发货，未发完
            if ("4".equals(scmPoItemEntity.getItemStatus()) || "2".equals(scmPoItemEntity.getItemStatus())) {
                deliverEntity.setDeliverTime(date); // 系统时间
                deliverEntity.setItemNo(scmPoItemVo.getItemNo());// 发货行项目号
                deliverEntity.setPoItemId(scmPoItemVo.getPoItemId()); // 行项目的id
                deliverEntity.setPoNo(scmPoItemVo.getPoNo()); // 订单号
                deliverEntity.setShippedQty(BigDecimal.valueOf(Integer.parseInt(map.get(key)))); // 发货数量
                //第一次发货则创建新记录，再次发货时更新
                if ("4".equals(scmPoItemEntity.getItemStatus())) {
                    deliverEntity.setPkId(SunnykidText.getUUID());// 流水id
                } else {
                    deliverEntity.setPkId(scmPoItemVo.getDeliverId());// 流水id
                    //多次分批发货，累计发货数量
                    BigDecimal num = new BigDecimal(Double.parseDouble(scmPoItemVo.getShippedQty().toString()));
                    deliverEntity.setShippedQty(deliverEntity.getShippedQty().add(num));
                }
                // 待发数量和本次发货数量做 比较
                if (scmPoItemVo.getBackOrders().compareTo(BigDecimal.valueOf(Integer.parseInt(map.get(key)))) > 0) {
                    scmPoItemEntity.setItemStatus("2");// 更新订单状态
                    deliverEntity.setStatus("2");
                }
                if (scmPoItemVo.getBackOrders().compareTo(BigDecimal.valueOf(Integer.parseInt(map.get(key)))) == 0) {
                    scmPoItemEntity.setItemStatus("3");// 更新订单状态
                    deliverEntity.setStatus("3");
                }
                if (scmPoItemVo.getBackOrders().compareTo(BigDecimal.valueOf(Integer.parseInt(map.get(key)))) == -1) {

                    return R.ok().put("result", "本次发货的数量大于待发货的数量");
                }

                this.scmPoItemService.updateById(scmPoItemEntity);

                this.deliverService.insertOrUpdate(deliverEntity);
                String fph = "F" + SunnykidText.getUUID();
                if ("".equals(deliverEntity.getEdition())) {
                    int tem = Integer.parseInt(deliverEntity.getEdition());
                    edition = tem++;
                } else {
                    edition++;
                }
                // 设置发货的版本号
                deliverEntity.setEdition(String.valueOf(edition));
                // 发货单号
                deliverEntity.setDeliverNo(fph);
                this.deliverService.updaeDeliver(deliverEntity);

                //发货记录
                DeliverRecordEntity record = new DeliverRecordEntity(fph, deliverEntity.getDeliverTime(), deliverEntity.getPoItemId(), deliverEntity.getPoNo(),
                        deliverEntity.getItemNo(), BigDecimal.valueOf(Integer.parseInt(map.get(key))), new Date());
                deliverRecordService.insert(record);
            } else {
                return R.ok().put("result", "发货失败");
            }
        }

        //返回前通过OA通知下单人已发货
        scmPoItemService.noticeApplier(itemEntityList, true);
        return R.ok();
    }

    /**
     * 订单取消
     */
    @SysLog("取消订单信息")
    @RequestMapping("/toRemove")
    @ResponseBody
    public R toRemove(@RequestParam(value = "ids[]") String[] ids) {
        if (ids == null || ids.length == 0) {
            return R.error();
        }
        String[] idList = ids;
        for (String pkId : idList) {
            ScmPoItemEntity ScmPoItemEntity = this.scmPoItemService.selectById(pkId);
            if ("0".equals(ScmPoItemEntity.getItemStatus()) || "1".equals(ScmPoItemEntity.getItemStatus())) {
                ScmPoItemEntity.setItemStatus("-1");
                this.scmPoItemService.insertOrUpdate(ScmPoItemEntity);
            } else {
                return R.ok().put("result", "订单已发货无法取消");
            }

        }
        return R.ok();
    }

    /**
     * 订单确认
     */
    @SysLog("确认订单信息")
    @RequestMapping("/toupdate")
    @ResponseBody
    public R toupdate(@RequestParam(value = "ids[]") String[] ids) {
        if (ids == null || ids.length == 0) {
            return R.error();
        }
        String[] idList = ids;
        for (String pkId : idList) {
            ScmPoItemEntity ScmPoItemEntity = this.scmPoItemService.selectById(pkId);
            ScmPoItemEntity.setItemStatus("1");
            this.scmPoItemService.updateById(ScmPoItemEntity);
        }
        return R.ok();
    }

    /**
     * 更改供应商回复交期
     */
    @SysLog("更改供应商回复交期")
    @RequestMapping("/updateReplyDate")
    @ResponseBody
    public R updateReplyDate(@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "replyDate") String replyDate) throws ParseException {
        List<ScmPoItemEntity> ScmPoItemList = this.scmPoItemService.selectBatchIds(Arrays.asList(ids));
        Date df = new SimpleDateFormat("yyyy-MM-dd").parse(replyDate);
        ScmPoItemList.forEach(scmPoItem -> scmPoItem.setReplyDate(df));
        boolean b = this.scmPoItemService.updateBatchById(ScmPoItemList);
        if (!b) {
            return R.error("更新失败，请重试！");
        }
        return R.ok();
    }

    /**
     * 发货
     */
    @SysLog("订单发送")
    @RequestMapping("/toSend")
    @ResponseBody
    public R toSend(@RequestParam(value = "ids[]") String[] ids) throws Exception_Exception {
        int edition = 0;
        if (ids == null || ids.length == 0) {
            return R.error();
        }
        List<String> liststr = new ArrayList<String>();
        //获取订单item entity，获取物料描述 通知下单人
        List<ScmPoItemEntity> itemEntityList = new ArrayList<>();
        // 分批发货的时间
        Date date = DateUtils.stringToDate(DateUtils.format(DateUtils.currentDateTime()), DateUtils.DATE_PATTERN);
        for (String pkId : ids) {
            // 发货的数据
            DeliverEntity deliverEntity = new DeliverEntity();
            ScmPoItemVo scmPoItemVo = this.scmPoItemService.selectByIdVo(pkId);
            ScmPoItemEntity scmPoItemEntity = this.scmPoItemService.selectById(pkId);
            deliverEntity.setPkId(SunnykidText.getUUID());// 流水id
            deliverEntity.setDeliverTime(date); // 系统时间
            deliverEntity.setItemNo(scmPoItemVo.getItemNo());// 发货行项目号
            deliverEntity.setPoItemId(scmPoItemVo.getPoItemId()); // 行项目的id
            deliverEntity.setPoNo(scmPoItemVo.getPoNo()); // 订单号
            // 应该时待发货的数量
            deliverEntity.setShippedQty(scmPoItemVo.getBackOrders()); // 发货数量
            scmPoItemEntity.setItemStatus("3");// 更新订单状态
            deliverEntity.setStatus("3");
            this.scmPoItemService.updateById(scmPoItemEntity);
            boolean b = this.deliverService.insertOrUpdate(deliverEntity);
            if (b) {
                liststr.add(scmPoItemVo.getPoItemId());
            }
            itemEntityList.add(scmPoItemEntity);
        }
        String fph = "F" + SunnykidText.getUUID();
        List<DeliverEntity> deliverEntitylist = null;
        if (liststr.size() > 0) {
            deliverEntitylist = this.deliverService.findById(liststr);
        }
        for (DeliverEntity deliver : deliverEntitylist) {
            if ("".equals(deliver.getEdition())) {
                int tem = Integer.parseInt(deliver.getEdition());
                edition = tem++;
            } else {
                edition++;
            }
            deliver.setEdition(String.valueOf(edition)); // 设置发货的版本号
            deliver.setDeliverNo(fph); // 发货单号
            this.deliverService.updaeDeliver(deliver);
            //发货记录
            DeliverRecordEntity record = new DeliverRecordEntity(fph, deliver.getDeliverTime(), deliver.getPoItemId(), deliver.getPoNo(),
                    deliver.getItemNo(), deliver.getShippedQty(), new Date());
            deliverRecordService.insert(record);
        }

        //返回前通过OA通知下单人已发货
        scmPoItemService.noticeApplier(itemEntityList, false);
        return R.ok();
    }

    @RequestMapping("/toDwnload")
    public void toDwnload(HttpServletResponse response, HttpServletRequest request) {
        // 设置文件名，根据业务需要替换成要下载的文件名
        String pkId = request.getParameter("id").trim();
        ScmPoItemEntity ScmPoItemEntity = this.scmPoItemService.selectById(pkId);
        DeliverEntity deliver = this.deliverService.selectByItemId(ScmPoItemEntity.getPoItemId());
        String url = deliver.getPhotoUrl();
        String fileName = url.substring(url.lastIndexOf("\\") + 1);
        if (fileName != null) {
            // 设置文件路径
            String realPath = SysConfig.getUploadPath();
            File file = new File(realPath, fileName);
            if (file.exists()) {
                FileTransfer ft = new FileTransfer(request, response);
                try {
                    ft.downloadFile(file, file.getName());
                } catch (TransferException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 跳转至供应商编辑页面
     *
     * @param
     * @return
     */
    @RequestMapping("/toSendBatch/{poFlag}/{ids}/{status}")
    public ModelAndView toSendBatch(@PathVariable("poFlag") String poFlag, @PathVariable("ids") String ids, @PathVariable("status") String status) {
        // 把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/orders/" + poFlag.toLowerCase() + "_send_batch");
        modelAndView.addObject("ids", ids);
        modelAndView.addObject("status", status);
        return modelAndView;
    }

    /**
     * @Description 订单同步SAP方法
     * @Param [ids]
     * @Return com.hs.srm.common.utils.R
     * @Author socik
     * @Date 2019/5/5 14:41
     */
    @SysLog("订单同步sap")
    @RequestMapping("/toSendSap")
    @ResponseBody
    public R toSendSap(@RequestParam(value = "ids[]") String[] ids) {
        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList importList = null;
        JCoParameterList tables = null;
        List<String> idList = Arrays.asList(ids);
        if (ids == null || ids.length == 0) {
            return R.error();
        }

        //通过ids找出所有订单，要求必须同一订单号，且多个行项目必须一起同步SAP
        List<ScmPoItemEntity> itemEntityList = scmPoItemService.selectBatchIds(idList);
        //按行项目排序,00010,00020...
        itemEntityList.sort(Comparator.comparing(ScmPoItemEntity::getItemNo));
        Set<String> set = new HashSet<>(itemEntityList.stream().map(ScmPoItemEntity::getPoNo).collect(Collectors.toList()));
        if (set.size() != 1) {
            return R.error("相同采购凭证号才能同步SAP");
        }
        //根据订单号找同一订单的行项目，过滤删除的订单
        int items = scmPoItemService.selectCount(new EntityWrapper<ScmPoItemEntity>()
                .eq("po_no", itemEntityList.get(0).getPoNo()).ne("delete_flag", 1));
        if (items != itemEntityList.size()) {
            return R.error("相同采购凭证号的多个行项目必须一起同步SAP");
        }

        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZBAPI_PO_CREATE1");
            //获取RFC返回的字段值
            tables = function.getTableParameterList();
            importList = function.getImportParameterList();//入参设置
        } catch (JCoException e) {
            e.printStackTrace();
        }
        // 订单抬头参数POHEADER
        JCoStructure value_desc = importList.getStructure("POHEADER");
        // 订单抬头参数POHEADERX
        JCoStructure value_descx = importList.getStructure("POHEADERX");
        //保存scmPoItemEntity，同步SAP成功后修改订单状态
        List<ScmPoItemEntity> scmPoItemList = new ArrayList<>();
        if (idList.size() > 0) {
            ScmPoItemEntity scmPoItem = this.scmPoItemService.selectById(idList.get(0));
            ScmPoHeaderEntity scmPoHeaderEntity = this.scPoHeaderService.getByPoNo(scmPoItem.getPoNo());
            // 公司代码 配置表
            value_desc.setValue("COMP_CODE", scmPoHeaderEntity.getCompanyCode());
            //采购订单号
            value_desc.setValue("PO_NUMBER", scmPoItem.getPoNo());
            // 采购凭证类型
            value_desc.setValue("DOC_TYPE", "ZBZ");
            // 采购组织
            value_desc.setValue("PURCH_ORG", scmPoHeaderEntity.getPurchOrg());
            // 采购组
            value_desc.setValue("PUR_GROUP", scmPoHeaderEntity.getPurchGroup());
            // 供应商 配置表
            value_desc.setValue("VENDOR", "00000" + scmPoHeaderEntity.getVendorId());
            // 供应商 配置表
            value_desc.setValue("PMNTTRMS", scmPoHeaderEntity.getPayCondition());
            value_desc.setValue("CURRENCY", scmPoHeaderEntity.getCurrencyCode());
            value_desc.setValue("CURRENCY_ISO", scmPoHeaderEntity.getCurrencyCode());
            value_descx.setValue("CURRENCY", "X");
            value_descx.setValue("CURRENCY_ISO", "X");
            // 设置采购行项目参数，用指定行项目
            value_desc.setValue("ITEM_INTVL", "00010");
            value_descx.setValue("PO_NUMBER", "X");
            value_descx.setValue("ITEM_INTVL", "X");
            value_descx.setValue("COMP_CODE", "X");
            value_descx.setValue("DOC_TYPE", "X");
            value_descx.setValue("PURCH_ORG", "X");
            value_descx.setValue("PUR_GROUP", "X");
            value_descx.setValue("VENDOR", "X");
            value_descx.setValue("VENDOR", "X");
            value_descx.setValue("PMNTTRMS", "X");
            //遍历RFC返回的表对象
            // 交货日期
            //JCoTable table = tables.getTable("POSCHEDULE");
            //JCoTable tablex = tables.getTable("POSCHEDULEX");
            // 行项目参数POITEM：
            JCoTable table2 = tables.getTable("POITEM");
            // 行项目参数POITEMX
            JCoTable table3 = tables.getTable("POITEMX");
            //备注表
            JCoTable table6 = tables.getTable("POTEXTITEM");
            //交货日期表
            JCoTable table7 = tables.getTable("POSCHEDULE");
            JCoTable table8 = tables.getTable("POSCHEDULEX");
            // 非生产性成本中心数据
            JCoTable table4 = tables.getTable("POACCOUNT");
            JCoTable table5 = tables.getTable("POACCOUNTX");

            //送货地址
            JCoTable poaddrdelivery = tables.getTable("POADDRDELIVERY");

            //多个订单循环插入，订单同步SAP顺序要按行项目从小到大
            for (ScmPoItemEntity scmPoItemEntity : itemEntityList) {
                scmPoItemEntity.setItemStatus("4");
                scmPoItemList.add(scmPoItemEntity);
                //生产性的先确定信息记录有没有同步sap
                EssentialInformationEntity essential = essentialInformation.selectOne(new EntityWrapper<EssentialInformationEntity>()
                        .eq("material_code", scmPoItemEntity.getMaterialCode())
                        .eq("srm_code", scmPoHeaderEntity.getVendorId()));
                //信息记录未确认，返回通知
                if (essential != null && essential.getInfoStatus() == EssentialInformationEntity.WQR) {
                    return R.error("该物料号：" + scmPoItemEntity.getMaterialCode() + " 的信息记录未确认，不能同步sap！");
                }
              /*  table.appendRow();
                tablex.appendRow();
                table.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                table.setValue("DELIVERY_DATE", DateUtils.format(scmPoItemEntity.getDeliveryDate(), DateUtils.DATE_TIME_ALL_SAP));
                tablex.setValue("DELIVERY_DATE", "X");
                tablex.setValue("PO_ITEM", scmPoItemEntity.getItemNo());*/
                table2.appendRow();
                table2.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                table2.setValue("PLANT", scmPoItemEntity.getFactory()); //工厂 配置表offset = {int[2][]@15693}
                table2.setValue("BATCH", "");// 批号
                table2.setValue("QUANTITY", scmPoItemEntity.getPoCount());// 数量
                table2.setValue("TAX_CODE", scmPoItemEntity.getTaxCode());// 税码
                table2.setValue("VEND_MAT", scmPoItemEntity.getPoNo());
                table2.setValue("PREQ_NAME", scmPoItemEntity.getRequester());

                table3.appendRow();
                table3.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                table3.setValue("PO_ITEMX", "X");// 订单项目
                table3.setValue("PLANT", "X"); //工厂
                table3.setValue("VEND_MAT", "X");
                table3.setValue("BATCH", "X");// 批号
                table3.setValue("QUANTITY", "X");// 数量
                table3.setValue("TAX_CODE", "X");//
                table3.setValue("PREQ_NAME", "X");
                if (scmPoItemEntity.getFree() == 1) {
                    table2.setValue("FREE_ITEM", "X");
                    table3.setValue("FREE_ITEM", "X");
                }
                //备注不空则传入，生产性的没有备注会自动从申请单中关联，所以备注为空则不能设值
                if (StringUtils.isNotBlank(scmPoItemEntity.getRemark())) {
                    table6.appendRow();
                    table6.setValue("TEXT_ID", "F01");
                    table6.setValue("TEXT_LINE", scmPoItemEntity.getRemark());
                    table6.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                }

                table7.appendRow();
                table8.appendRow();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                table7.setValue("DELIVERY_DATE", simpleDateFormat.format(scmPoItemEntity.getReplyDate()));
                table8.setValue("DELIVERY_DATE", "X");
                table7.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                table8.setValue("PO_ITEM", scmPoItemEntity.getItemNo());

                //地址不空，则设置收货地址，0000023050工业厂；0000023052福仕厂；0000054814平巷
                if (StringUtils.isNotBlank(scmPoItemEntity.getDeliveryAddress())) {
                    poaddrdelivery.appendRow();
                    poaddrdelivery.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    poaddrdelivery.setValue("ADDR_NO", scmPoItemEntity.getDeliveryAddress());
                }

                //判断是否为生产性订单还是非生产性订单
                if ("PRO".equals(scmPoHeaderEntity.getPoFlag())) {
                    //库存地点 配置表
                    table2.setValue("STGE_LOC", scmPoItemEntity.getStorageLocation());
                    // 物料
                    table2.setValue("MATERIAL", "0000000000" + scmPoItemEntity.getMaterialCode());
                    /*订单价格等数据不用SAP中信息记录中的数据，直接传过去，代码先注释，需要时再修改*/
                    /*if (scmPoItemEntity.getInfoCode() != null) {
                        //传输信息记录
                        table2.setValue("INFO_REC", scmPoItemEntity.getInfoCode());
                        //传输信息记录
                        table3.setValue("INFO_REC", "X");
                    } else*/
                    {
                        //采购计量单位
                        table2.setValue("PO_UNIT", scmPoItemEntity.getPoUnit());
                        //价格 ,去除末尾0
                        BigDecimal poPrice = new BigDecimal(scmPoItemEntity.getPoPrice().stripTrailingZeros().toPlainString());
                        //价格小数点位数
                        int decimalPoint = poPrice.scale();
                        //小数点超过两位，价格和价格单位同时扩大
                        //如果货币为日元和泰朱
                        if (scmPoHeaderEntity.getCurrencyCode().equals("THB") || scmPoHeaderEntity.getCurrencyCode().equals("JPY")) {
                            if (decimalPoint > 0) {
                                poPrice = poPrice.movePointRight(decimalPoint);
                                //价格单位
                                table2.setValue("PRICE_UNIT", new Double(Math.pow(10, decimalPoint)).intValue());
                            } else {
                                //价格单位
                                table2.setValue("PRICE_UNIT", 1);
                            }

                        } else {
                            if (decimalPoint > 2) {
                                poPrice = poPrice.movePointRight(decimalPoint - 2);
                                //价格单位
                                table2.setValue("PRICE_UNIT", new Double(Math.pow(10, decimalPoint - 2)).intValue());
                            } else {
                                //价格单位
                                table2.setValue("PRICE_UNIT", 1);
                            }
                        }
                        table2.setValue("NET_PRICE", poPrice);
                        table2.setValue("ORDERPR_UN", scmPoItemEntity.getPoUnit());
                        table2.setValue("ORDERPR_UN_ISO", scmPoItemEntity.getPoUnit());
                        //价格
                        table3.setValue("NET_PRICE", "X");
                        //价格单位
                        table3.setValue("PRICE_UNIT", "X");
                        //采购计量单位
                        table3.setValue("PO_UNIT", "X");
                    }
                    //采购申请行项目
                    table2.setValue("PREQ_ITEM", scmPoItemEntity.getPrItemNo());
                    //采购申请
                    table2.setValue("PREQ_NO", scmPoItemEntity.getPrNo());
                    //库存地点
                    table3.setValue("STGE_LOC", "X");
                    table3.setValue("MATERIAL", "X");

                    table3.setValue("PREQ_ITEM", "X");
                    table3.setValue("PREQ_NO", "X");

                } else {
                    table4.appendRow();
                    //描述文本
                    table2.setValue("SHORT_TEXT", scmPoItemEntity.getMaterialDesc());
                    //采购计量单位
                    table2.setValue("PO_UNIT", scmPoItemEntity.getPoUnit());
                    //价格 ,去除末尾0
                    BigDecimal poPrice = new BigDecimal(scmPoItemEntity.getPoPrice().stripTrailingZeros().toPlainString());
                    //价格小数点位数
                    int decimalPoint = poPrice.scale();
                    //小数点超过两位，价格和价格单位同时扩大
                    if (decimalPoint > 2) {
                        poPrice = poPrice.movePointRight(decimalPoint - 2);
                        //价格单位
                        table2.setValue("PRICE_UNIT", new Double(Math.pow(10, decimalPoint - 2)).intValue());
                    } else {
                        //价格单位
                        table2.setValue("PRICE_UNIT", 1);
                    }
                    table2.setValue("NET_PRICE", poPrice);
                    //物料组
                    table2.setValue("MATL_GROUP", scmPoItemEntity.getMaterialGroup());
                    //科目类别
                    table2.setValue("ACCTASSCAT", scmPoItemEntity.getSubjectCategory());
                    //描述文本
                    table3.setValue("SHORT_TEXT", "X");
                    //物料组
                    table3.setValue("MATL_GROUP", "X");
                    //价格
                    table3.setValue("NET_PRICE", "X");
                    //价格单位
                    table3.setValue("PRICE_UNIT", "X");
                    //科目类别
                    table3.setValue("ACCTASSCAT", "X");
                    //采购计量单位
                    table3.setValue("PO_UNIT", "X");
                    //订单行项目
                    table4.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    //成本中心
                    table4.setValue("COSTCENTER", scmPoItemEntity.getCostCenter());
                    // 固定字段1
                    table4.setValue("SERIAL_NO", "1");
                    table4.setValue("QUANTITY", scmPoItemEntity.getPoCount());
                    //总账科目，放入物料编码字段，同步SAP时从物料编码中取出总账科目
                    table4.setValue("GL_ACCOUNT", "00" + scmPoItemEntity.getMaterialCode());
                    table4.setValue("CO_AREA", "1000");
                    table4.setValue("ORDERID", scmPoItemEntity.getInternalPoNo());
                    //固定资产编号
                    table4.setValue("ASSET_NO", scmPoItemEntity.getFixedAssetsNo());
                    //固定资产次级号
                    table4.setValue("SUB_NUMBER", scmPoItemEntity.getFixedAssetsSubno());
                    table5.appendRow();
                    table5.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    //成本中心
                    table5.setValue("COSTCENTER", "X");
                    // 固定字段1
                    table5.setValue("SERIAL_NO", "1");
                    table5.setValue("GL_ACCOUNT", "X");
                    table5.setValue("CO_AREA", "X");
                    table5.setValue("QUANTITY", "X");
                    table5.setValue("ORDERID", "X");
                    table5.setValue("ASSET_NO", "X");
                    table5.setValue("SUB_NUMBER", "X");
                }
            }
        }
        try {
            function.execute(destination);
        } catch (JCoException e) {
            logger.error("创建采购订单出错", e);
            throw new RuntimeException("SAP调用异常");
        }
        JCoTable returnTable = tables.getTable("RETURN");
        String returnerror = "";
        boolean flag = true;
        for (int i = 0; i < returnTable.getNumRows(); i++) {
            returnTable.setRow(i);
            if ("E".equals(returnTable.getString("TYPE")) || "A".equals(returnTable.getString("TYPE"))) {
                returnerror += returnTable.getString("ID") + ":" + returnTable.getString("MESSAGE") + ";";
                logger.error(returnerror);
                flag = false;
            }
        }
        if (!flag) {
            return R.error("创建采购订单失败-" + returnerror);
        }
        //更新订单状态
        this.scmPoItemService.updateBatchById(scmPoItemList);
        return R.ok("同步成功!");
    }

    /**
     * 修改订单SAP方法
     *
     * @param ids       订单行id
     * @param poCount   数量
     * @param replyDate 交期
     * @param price     价格
     * @param limitFull 过量交货限度
     * @param limitLess 交货不足限度
     * @return
     * @throws ParseException
     */
    @SysLog("修改订单SAP方法")
    @RequestMapping("/toUpdateSap")
    @ResponseBody
    public R toUpdateSap(@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "poCount", required = false) String poCount
            , @RequestParam(value = "replyDate", required = false) String replyDate, @RequestParam(value = "poPrice", required = false) String price,
                         @RequestParam(value = "limitFull", required = false) String limitFull, @RequestParam(value = "limitLess", required = false) String limitLess) throws ParseException {
        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList importList = null;
        JCoParameterList tables = null;
        String[] idList = ids;
        if (ids == null || ids.length == 0) {
            return R.error();
        }
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZBAPI_PO_CHANGE");
            tables = function.getTableParameterList();
            importList = function.getImportParameterList();
        } catch (
                JCoException e) {
            e.printStackTrace();
        }
        // 订单抬头参数POHEADER
        JCoStructure value_desc = importList.getStructure("POHEADER");
        // 订单抬头参数POHEADERX
        JCoStructure value_descx = importList.getStructure("POHEADERX");
        JCoTable itemTbl = tables.getTable("POITEM");
        JCoTable itemTblx = tables.getTable("POITEMX");
        //交货日期表
        JCoTable deliverDate = tables.getTable("POSCHEDULE");
        JCoTable deliverDatex = tables.getTable("POSCHEDULEX");
        //改价格表
        JCoTable priceChange = tables.getTable("POCOND");
        JCoTable priceChangex = tables.getTable("POCONDX");

        for (String pkId : idList) {
            ScmPoItemEntity scmPoItemEntity = this.scmPoItemService.selectById(pkId);
            //采购变更: 回复交期、数量
            if (StringUtils.isNotBlank(poCount) || StringUtils.isNotBlank(replyDate)) {
                scmPoItemEntity.setPoCount(new BigDecimal(poCount));
                scmPoItemEntity.setReplyDate(new SimpleDateFormat("yyyy-MM-dd").parse(replyDate));
            } else if (StringUtils.isNotBlank(price)) {//价格不为空：价格变更
                if (new BigDecimal(price).compareTo(scmPoItemEntity.getPoPrice()) != 0) {
                    scmPoItemEntity.setPoPrice(new BigDecimal(price));
                }
            } else if (StringUtils.isNotBlank(limitLess) || StringUtils.isNotBlank(limitFull)) {//交货限度
                scmPoItemEntity.setLimitFull(limitFull);
                scmPoItemEntity.setLimitLess(limitLess);
            }

            ScmPoHeaderEntity scmPoHeaderEntity = this.scPoHeaderService.getByPoNo(scmPoItemEntity.getPoNo());
            // 公司代码 配置表
            value_desc.setValue("COMP_CODE", scmPoItemEntity.getFactory());
            if (scmPoItemEntity.getFactory().equals("8001") || scmPoItemEntity.getFactory().equals("8002") || scmPoItemEntity.getFactory().equals("8003")) {
                value_desc.setValue("COMP_CODE", "8888");
            }
            //采购订单号
            //value_desc.setValue("PO_NUMBER", scmPoItemEntity.getPoNo());
            importList.setValue("PURCHASEORDER", scmPoItemEntity.getPoNo());
            // 采购凭证类型
            value_desc.setValue("DOC_TYPE", "ZBZ");
            // 采购组织 , 除1700和1800，其他工厂采购组织1000,1700和1800采购组织1400
            value_desc.setValue("PURCH_ORG", scmPoHeaderEntity.getPurchOrg());
            // 采购组
            value_desc.setValue("PUR_GROUP", scmPoHeaderEntity.getPurchGroup());
            // 供应商 配置表
            value_desc.setValue("VENDOR", "00000" + scmPoHeaderEntity.getVendorId());
            // 供应商 配置表
            value_desc.setValue("PMNTTRMS", scmPoHeaderEntity.getPayCondition());
            // 设置采购行项目参数，用指定行项目
            value_desc.setValue("ITEM_INTVL", scmPoItemEntity.getItemNo());
            value_descx.setValue("PO_NUMBER", "X");
            value_descx.setValue("ITEM_INTVL", "X");
            value_descx.setValue("COMP_CODE", "X");
            value_descx.setValue("DOC_TYPE", "X");
            value_descx.setValue("PURCH_ORG", "X");
            value_descx.setValue("PUR_GROUP", "X");
            value_descx.setValue("VENDOR", "X");
            value_descx.setValue("VENDOR", "X");
            value_descx.setValue("PMNTTRMS", "X");

            //价格变更
            if (StringUtils.isNotBlank(price)) {
                priceChange.appendRow();
                priceChangex.appendRow();
                //行项目
                priceChange.setValue("ITM_NUMBER", scmPoItemEntity.getItemNo());
                priceChangex.setValue("ITM_NUMBER", scmPoItemEntity.getItemNo());

                //货币
                priceChange.setValue("CURRENCY", scmPoHeaderEntity.getCurrencyCode());
                priceChangex.setValue("CURRENCY", "X");

                //默认设置
                priceChange.setValue("COND_COUNT", "01");
                priceChangex.setValue("COND_COUNT", "X");
                priceChange.setValue("COND_TYPE", "PBXX");
                priceChangex.setValue("COND_TYPE", "X");
                priceChange.setValue("CHANGE_ID", "U");
                priceChangex.setValue("CHANGE_ID", "X");
                //价格 ,去除末尾0
                BigDecimal poPrice = new BigDecimal(scmPoItemEntity.getPoPrice().stripTrailingZeros().toPlainString());
                //价格小数点位数
                int decimalPoint = poPrice.scale();
                //小数点超过两位，价格和价格单位同时扩大

                if (scmPoHeaderEntity.getCurrencyCode().equals("THB") || scmPoHeaderEntity.getCurrencyCode().equals("JPY")) {
                    if (decimalPoint > 0) {
                        poPrice = poPrice.movePointRight(decimalPoint);
                        //价格单位
                        priceChange.setValue("COND_P_UNT", new Double(Math.pow(10, decimalPoint)).intValue());
                    } else {
                        //价格单位
                        priceChange.setValue("COND_P_UNT", 1);
                    }

                } else {
                    if (decimalPoint > 2) {
                        poPrice = poPrice.movePointRight(decimalPoint - 2);
                        //价格单位
                        priceChange.setValue("COND_P_UNT", new Double(Math.pow(10, decimalPoint - 2)).intValue());
                    } else {
                        //价格单位
                        priceChange.setValue("COND_P_UNT", 1);
                    }
                }
                priceChange.setValue("COND_VALUE", poPrice);
                //价格
                priceChangex.setValue("COND_VALUE", "X");
                //价格单位
                priceChangex.setValue("COND_P_UNT", "X");
            } else {
                //交期、数量修改
                if (StringUtils.isNotBlank(poCount) || StringUtils.isNotBlank(replyDate)) {
                    itemTbl.appendRow();
                    itemTblx.appendRow();
                    //行项目
                    itemTbl.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    itemTblx.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    itemTblx.setValue("PO_ITEMX", "X");

                    // 数量
                    itemTbl.setValue("QUANTITY", scmPoItemEntity.getPoCount());
                    itemTblx.setValue("QUANTITY", "X");
                    //回复交期
                    deliverDate.appendRow();
                    deliverDatex.appendRow();
                    deliverDate.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    deliverDatex.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    deliverDatex.setValue("PO_ITEMX", "X");
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    deliverDate.setValue("DELIVERY_DATE", simpleDateFormat.format(scmPoItemEntity.getReplyDate()));
                    deliverDatex.setValue("DELIVERY_DATE", "X");

                } else {//交货限度修改
                    itemTbl.appendRow();
                    itemTblx.appendRow();
                    //行项目
                    itemTbl.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    itemTblx.setValue("PO_ITEM", scmPoItemEntity.getItemNo());
                    itemTblx.setValue("PO_ITEMX", "X");

                    //过量交货限度
                    itemTbl.setValue("OVER_DLV_TOL", scmPoItemEntity.getLimitFull());
                    itemTblx.setValue("OVER_DLV_TOL", "X");
                    //交货不足限度
                    itemTbl.setValue("UNDER_DLV_TOL", scmPoItemEntity.getLimitLess());
                    itemTblx.setValue("UNDER_DLV_TOL", "X");
                }
            }
            try {
                function.execute(destination);
            } catch (JCoException e) {
                logger.error("创建采购订单出错", e);
                throw new RuntimeException("SAP调用异常");
            }
            JCoTable returnTable = tables.getTable("RETURN");
            String returnerror = "";
            boolean flag = true;
            for (int i = 0; i < returnTable.getNumRows(); i++) {
                returnTable.setRow(i);
                if ("E".equals(returnTable.getString("TYPE")) || "A".equals(returnTable.getString("TYPE"))) {
                    returnerror += returnTable.getString("ID") + ":" + returnTable.getString("MESSAGE") + ";";
                    logger.error(returnerror);
                    flag = false;
                }
            }
            if (!flag) {
                return R.error("创建采购订单失败-" + returnerror);
            }
            scmPoItemEntity.setItemStatus("4");
            this.scmPoItemService.updateById(scmPoItemEntity);
        }
        return R.ok("同步成功!");
    }

    /**
     * 报告上传
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public R upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //上传报告
        MultipartFile multipartFile = multipartRequest.getFile("reportFile");
        //上传文件名添加时间后缀 ！！！！！！！！！！！！！！！！！！！！！！！不要改时间后缀格式，不要改、不要改！！！！！！！！！！
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("_yyyy-MM-dd");
        String StrDate = simpleDateFormat.format(new Date());
        String originalFilename = multipartFile.getOriginalFilename();
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/orders/";
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + StrDate + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String filePath = fileDir + fileName;
        boolean result = FileUtils.fileUpload(fileDir, fileName, multipartFile);
        //保存失败
        if (!result) {
            return R.error();
        }
        Integer pu = scmPoItemService.saveUploadFilePath(request, filePath);
        return R.ok(pu);
    }

    //报告下载
    @RequestMapping("/downloadFile")
    @ResponseBody
    public R download(@RequestParam(value = "files") String[] filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {
        //文件下载，多文件打包zip下载,单文件直接下载
        if (filePath.length > 1) {
            FileUtils.zipDownload(filePath, "文件下载", request, response);
        } else {
            FileUtils.fileDownload(filePath[0], request, response);
        }
        return R.ok();
    }

    /**
     * 删除订单
     *
     * @param itemIds
     * @param type
     * @return
     */
    @SysLog("删除订单")
    @ResponseBody
    @RequestMapping("/deleteOrders")
    public R deleteOrders(@RequestParam(value = "itemIds") String[] itemIds, @RequestParam(value = "type") String type) {
        String result = scmPoItemService.deleteOrders(type, itemIds);
        if (StringUtils.isBlank(result)) {
            return R.ok();
        }
        return R.error(result);
    }


    /**
     * 生成送货单
     *
     * @param pkIds 订单id
     * @return
     */
    @SysLog("生成送货单")
    @ResponseBody
    @PostMapping("/deliverOrder")
    public R deliverOrder(@RequestParam(value = "ids[]") String[] pkIds) throws IOException {
        return scmPoItemService.deliverOrder(Arrays.asList(pkIds));
    }

    /**
     * 出货检测报告上传
     */
    @RequestMapping(value = "/uploadTestFile", method = RequestMethod.POST)
    @ResponseBody
    public R uploadTestFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //上传报告
        MultipartFile multipartFile = multipartRequest.getFile("reportFile");
        String StrDate = new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date());
        String originalFilename = multipartFile.getOriginalFilename();
        //文件保存路径
        String fileDir = SysConfig.getUploadPath() + "/orders/";
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + StrDate + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String filePath = fileDir + fileName;
        boolean result = FileUtils.fileUpload(fileDir, fileName, multipartFile);
        //保存失败
        if (!result) {
            return R.error();
        }
        String poItemId = request.getParameter("poItemId");
        OrderFileEntity orderFileEntity = new OrderFileEntity(poItemId, fileName, "/orders/" + fileName, new Date());
        scmPoItemService.updateById(new ScmPoItemEntity(poItemId, 1));
        boolean pu = orderFileService.insert(orderFileEntity);
        return R.ok(pu);
    }

    /**
     * 根据文件id下载送货单或出货检测报告
     *
     * @param id
     * @param response
     * @param request
     */
    @GetMapping("/downloadDeliverOrTest")
    public void downloadDeliverFileById(String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        OrderFileEntity orderFileEntity = orderFileService.selectById(id);
        if (ObjectUtils.allNotNull(orderFileEntity)) {
            FileUtils.fileDownload(SysConfig.getUploadPath() + orderFileEntity.getFilePath(), request, response);
        }
    }

    /**
     * 根据文件id查找所有文件
     *
     * @param id
     */
    @RequestMapping("/findDownloadDeliverOrTest")
    @ResponseBody
    public R findDownloadDeliverFileById(@RequestParam("id") String id) {
        List<OrderFileEntity> entities = this.orderFileService.findAllFile(id);
        return R.ok(entities);
    }

    @ResponseBody
    @PostMapping("/setFree")
    public R setFree(@RequestParam(value = "poItemId[]") String[] poItemIds) {

        for (String poItemId : poItemIds) {
            ScmPoItemEntity scmPoItemEntity = this.scmPoItemService.selectById(poItemId);
            scmPoItemEntity.setFree(1);
            scmPoItemEntity.setPoPrice(BigDecimal.ZERO);
            this.scmPoItemService.updateById(scmPoItemEntity);
        }
        return R.ok();
    }

    @ResponseBody
    @RequestMapping("/findmatericalCode")
    public R findmatericalCode(@RequestParam("materialCode") String materialCode) {
        List<ScmPoItemEntity> itemEntityList = this.scmPoItemService.selectList(new EntityWrapper<ScmPoItemEntity>().eq("material_code", materialCode));
        List<ScmPoItemEntity> itemEntities = new ArrayList<>();
        for (ScmPoItemEntity scmPoItemEntity : itemEntityList) {
            String poNo = scmPoItemEntity.getPoNo();
            ScmPoHeaderEntity headerEntity = this.scPoHeaderService.selectOne(new EntityWrapper<ScmPoHeaderEntity>().eq("po_no", poNo));
            VendorInfoEntity vendorInfoEntity = this.vendorService.selectOne(new EntityWrapper<VendorInfoEntity>().eq("sap_code", headerEntity.getVendorId()));
            scmPoItemEntity.setVendorCode(headerEntity.getVendorId());
            scmPoItemEntity.setVendorName(vendorInfoEntity.getVendorName());
            scmPoItemEntity.setCurrencyCode(vendorInfoEntity.getOrderCurrency());
            itemEntities.add(scmPoItemEntity);
        }
        return R.ok(itemEntities);
    }
}
